<template>
  <div class="map-container">
    <div id="map-box" style="width:100%;height:600px"></div>
<!--    <div class="station-list">-->
<!--      <h3>附近充电站（{{ stations.length }}个）</h3>-->
<!--      <ul>-->
<!--        <li v-for="(item, index) in stations" :key="index" @click="flyTo(item)">-->
<!--          {{ item.name }}<br>-->
<!--          <small>{{ item.lng }}, {{ item.lat }}</small>-->
<!--        </li>-->
<!--      </ul>-->
<!--    </div>-->
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import {StationPageList} from "@/api/station";
// import axios from 'axios'

const mapInstance = ref(null)

//获取经纬度 http://jingweidu.757dy.com/
const stations = ref([
    {
  "id": 1,
  "name": "北京市1号充电站",
  "lng": 116.397428,
  "lat": 39.90923,
  // 可扩展其他字段：充电桩类型、空闲数量等
},{
    "id": 2,
    "name": "北京市2号充电站",
    "lng": 116.398282,
    "lat": 39.911796,
    // 可扩展其他字段：充电桩类型、空闲数量等
  }
])
const AMap = ref(null)
const markers = ref([])

const search = ref({
  pageSize: 10,
  stationName: '',
  currentPage: 1,
  latitude:23.115149,
  longitude:113.254576
})

function getStationPageList(){
  StationPageList(search.value)
      .then(res => {
        console.info( res.data)
        if (res.data.code === 200000) {
          stations.value = res.data.data.data;
        } else {
          console.info('没有获取到了站点数据')
        }
      }).catch(error => {
    console.error('获取站点数据失败', error)
  });
}

// 配置参数
const config = {
  aMapKey: '933f222ff04a8a040f5a839930f5949c', // 高德API Key
  apiUrl: '/station/api/station/page' // 后端接口地址
}

onMounted(async () => {
  await loadAMapScript()
  initMap()
  getStationPageList();
  // fetchStations()
})

// 加载高德地图JS API
const loadAMapScript = () => {
  return new Promise((resolve) => {
    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${config.aMapKey}`
    script.onload = () => {
      AMap.value = window.AMap
      resolve()
    }
    document.head.appendChild(script)
  })
}

// 初始化地图
const initMap = () => {
  mapInstance.value = new AMap.value.Map('map-box', {
    zoom: 11,
    center: [113.254576, 23.115149] // 默认中心点
  })

  // 添加地图移动结束事件监听
  mapInstance.value.on('moveend', handleMapMove)
}

// 获取充电站数据
const fetchStations = async () => {
  console.info('==========================')
//   try {
//     const { res } = await axios.post(config.apiUrl, {
//       params: {
//         longitude: mapInstance.value.getCenter().lng,
//         latitude: mapInstance.value.getCenter().lat
//       }
//     })
//     stations.value = res.data.data.data;
  getStationPageList();
  console.info(stations.value)
    renderMarkers();
//   } catch (error) {
//     console.error('获取充电站数据失败:', error)
//   }
}

// 渲染地图标记
const renderMarkers = () => {
  // 清除旧标记
  markers.value.forEach(marker => marker.setMap(null))
  markers.value = []

  stations.value.forEach(station => {
    const marker = new AMap.value.Marker({
      position: new AMap.value.LngLat(station.longitude, station.latitude),
      map: mapInstance.value,
      content: createMarkerContent(station.stationName),
      offset: new AMap.value.Pixel(-15, -30)
    })
    markers.value.push(marker)
  })
}

// 创建自定义标记内容
const createMarkerContent = (name) => {
  return `<div class="custom-marker">
    <div class="icon">🔋</div>
    <div class="station-name" style="width: 200px; color: red;visibility: hidden;">${name}</div>
  </div>`
}

// 地图移动事件处理
const handleMapMove = () => {
  fetchStations()
}

// 定位到指定站点
// const flyTo = (station) => {
//   mapInstance.value.setZoomAndCenter(16, [station.lng, station.lat])
// }
</script>

<style>
.map-container {
  display: flex;
  gap: 20px;
  height: 600px;
}

.station-list {
  width: 300px;
  overflow-y: auto;
  border: 1px solid #eee;
  padding: 10px;
}

.station-list li {
  padding: 10px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.station-list li:hover {
  background: #f5f5f5;
}

.custom-marker {
  text-align: center;
}
.custom-marker .icon {
  font-size: 24px;
}
.custom-marker .station-name {
  font-size: 12px;
  white-space: nowrap;
}
.station-name:hover {
  visibility: visible;
}
</style>